<?php
/**
 * Created by PhpStorm.
 * User: xiaomeng
 * Date: 17-9-13
 * Time: 下午5:41
 */
namespace swf\socket;

use Medoo\Medoo;
use swf\core\Config;
use swf\core\syncDb;

class Common
{
    const BETTINGTIME = 50;
    const TOTALTIME = 60;

    static public $server;//服务
    static public $betting_time = self::BETTINGTIME;//投注时间
    static public $total_time = self::TOTALTIME;//总时间
    static public $open_status = 1;//状态[1=>'投注中',2=>'停止投注',3=>'开奖中',4=>'发奖']
    static public $no_id = null;//旗号
    static public $is_open = 0;//是否开奖 0：未开奖 1：已开奖
    static public $no_day;

    static public function init(\swoole_websocket_server $server)
    {
        self::$server = $server;
        //首次初始化配置
        if(is_null(self::$no_id))
        {
            syncDb::redis()->flushdb();//清空redis
            self::$server->task(json_encode(['cmd'=>'openRecord','data'=>'']));//更新开奖记录
            $_time = time();
            self::$no_day = date('d',$_time);
            //判断旗号是否生成
            $year = date('Y',$_time);
            $or_data =syncDb::mysql()->select("open_record_".$year,[
                "no_id"
            ],[
                "LIMIT"=>1,
                "ORDER"=>['created_at'=>"DESC"]
            ]);
            $or_data = $or_data[0]['no_id'];
            $_rq = date('y',$_time).date('m',$_time).date('d',$_time);
            if(isset($or_data) && substr($or_data,0,6) == $_rq)
            {
                $no_auto_id = (int)substr($or_data,6,9);
            } else {
                $no_auto_id = 0;
            }
            syncDb::redis()->set('no_auto_id',$no_auto_id);//旗号开始值
            self::$no_id = self::generateNoID();//旗号
            syncDb::redis()->set('room_auto_id',0);//房间号开始值


        }
        //首次开奖
        if(self::$is_open == 0 && self::$open_status == 1)
        {
            self::$server->task(json_encode(['cmd'=>'open','data'=>self::$no_id]));//开奖
            self::$is_open = 1;
        }

        \swoole_timer_tick(1000,function(){
            //更改旗号
            $current_day = date('d',time());
            if(self::$no_day != $current_day)
            {
                self::$no_day = $current_day;
                syncDb::redis()->set('no_auto_id',0);
            }

            if(self::$open_status == 1 || self::$open_status == 2)
            {   //投注中或者停止投注
                self::$betting_time -=1;
            }

            self::$total_time -=1;


            if(self::$betting_time == 48)
            {   //设置渠道列表
                $channel = syncDb::mysql()->select("channel",[
                    "channel_id"
                ],[
                    "is_usable"=>1
                ]);
                $channel_list = array_column($channel,"channel_id");
                syncDb::redis()->set("channel_list",json_encode($channel_list));
                //设置限投
                $limit_bet = syncDb::mysql()->select("limit_bet",['num','limit']);
                $limit_bet = array_column($limit_bet,"limit","num");
                syncDb::redis()->set("limit_bet",json_encode($limit_bet));
            }

            //停止投注
            if(self::$betting_time == 5){
                self::$open_status = 2;

                self::$server->task(json_encode(['cmd'=>'broadcastMsg','data'=>['send_cmd'=>'game_status','send_data'=>self::getGameStatus()]]));
                //派奖
                //按照渠道派将
                $open_num = syncDb::redis()->get('open_num');
                $open_num = explode('_',$open_num);
                $channel_list = syncDb::redis()->get("channel_list");
                $channel_list = json_decode($channel_list,true);
                foreach ($channel_list as $channel_id)
                {
                    self::$server->task(json_encode(['cmd'=>'prize','data'=>['channel_id'=>$channel_id,'open_num'=>$open_num[1],'no_id'=>$open_num[0]]]));
                }
            }

            //开奖中
            if(self::$betting_time == 0 && self::$total_time == 10){
                self::$open_status = 3;
                self::$server->task(json_encode(['cmd'=>'broadcastMsg','data'=>['send_cmd'=>'game_status','send_data'=>self::getGameStatus()]]));
            }
            //发奖
            if(self::$total_time == 5){
                self::$open_status = 4;
                self::$server->task(json_encode(['cmd'=>'openRecord','data'=>'']));//更新开奖记录
                self::$server->task(json_encode(['cmd'=>'broadcastMsg','data'=>['send_cmd'=>'game_status','send_data'=>self::getGameStatus()]]));
                self::$server->task(json_encode(['cmd'=>'tobet','data'=>['noId'=>self::$no_id,'userId'=>null]]));//去向章鱼发奖
                self::$server->task(json_encode(['cmd'=>'toprize','data'=>['noId'=>self::$no_id]]));//去向章鱼发离线用户奖
            }

            // 下一论
            if(self::$total_time == 0){
                self::$open_status = 1;
                self::$betting_time = self::BETTINGTIME;
                self::$total_time = self::TOTALTIME;
                self::$no_id = self::generateNoID();
                OperaBet::clearBet();//清空投注
                self::$server->task(json_encode(['cmd'=>'open','data'=>self::$no_id]));//再次开奖
                self::$server->task(json_encode(['cmd'=>'broadcastMsg','data'=>['send_cmd'=>'game_status','send_data'=>self::getGameStatus()]]));
            }


            //刷新游戏状态
            $game_status['sy_time'] = self::$betting_time;
            $game_status['game_status'] = self::getGameStatus();

            syncDb::redis()->set('game_status',json_encode($game_status));

        });
    }


    /**
     * 生成开奖旗号
     * @return string
     */
    static public function generateNoID()
    {
        $time = date('ymd',time());
        $no = syncDb::redis()->incr('no_auto_id');
        return $time.sprintf("%04d", $no);
    }

    /**
     * 公共的游戏状态 1.开奖状态 2.旗号 3.开奖号码
     * @return array
     */
    static public function getGameStatus()
    {
        $data = [];
        $data['open_status'] = self::$open_status;
        $data['no_id'] = self::$no_id;
        if($data['open_status'] == 3)
        {//获取开奖号码
            $open = syncDb::redis()->get('open_num');
            $open = explode('_',$open);
            $data['open_num'] = $open[1];
            $data['open_deg'] = $open[2];
        }
        return $data;
    }

}